package com.java110.mall.user.cmd.wechat;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.log.LoggerFactory;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.WechatConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;


@Java110Cmd(serviceCode = "wechat.wechatNotifyOpenId")
public class WechatNotifyOpenIdCmd extends Cmd {
    private final static Logger logger = LoggerFactory.getLogger(WechatNotifyOpenIdCmd.class);


    @Autowired
    private RestTemplate outRestTemplate;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        Assert.hasKeyAndValue(reqJson, "urlCode", "未包含跳转urlCode");
        Assert.hasKeyAndValue(reqJson, "code", "未包含跳转code");

    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext context, JSONObject reqJson) throws CmdException {

        String authCode = reqJson.getString("code");
        String paramStr = CommonCache.getAndRemoveValue(reqJson.getString("urlCode"));

        if (StringUtil.isEmpty(paramStr)) {
            context.setResponseEntity(ResultVo.redirectPage("/"));
            return;
        }

        JSONObject param = JSONObject.parseObject(paramStr);
        String redirectUrl = param.getString("redirectUrl");
        String appId = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppId");
        String appSecret = MappingCache.getValue(WechatConstant.MALL_WECHAT_DOMAIN, "wechatAppSecret");


        String url = WechatConstant.APP_GET_ACCESS_TOKEN_URL.replace("APPID", appId)
                .replace("SECRET", appSecret)
                .replace("CODE", authCode);

        ResponseEntity<String> paramOut = outRestTemplate.getForEntity(url, String.class);

        logger.debug("调用微信换去openId " + paramOut);
        if (paramOut.getStatusCode() != HttpStatus.OK) {
            context.setResponseEntity(ResultVo.redirectPage("/"));
        }
        JSONObject paramObj = JSONObject.parseObject(paramOut.getBody());
        //获取 openId
        String openId = paramObj.getString("openid");
        redirectUrl = redirectUrl + "&openId=" + openId;


        context.setResponseEntity(ResultVo.redirectPage(redirectUrl));

    }
}
